import React from 'react';
import { Select, Form } from 'antd';
import jsonp from 'fetch-jsonp';
import querystring from 'querystring';
import axios from './Engineering/axios';

import qs from 'qs'; //或者是querystringify
//todo kim-stamp qs用来解析     var obj = qs.parse('a=c'); assert.deepEqual(obj, { a: 'b' }   var str = qs.stringify(obj);  assert.equal(str, 'a=c');
//todo qs.parse('foo=bar&bar=foo') --->{ foo: 'bar', bar: 'foo' }    qs.parse('foo&bar=foo') ---> { foo: '', bar: 'foo' }    qs.stringify({ foo: bar });       // foo=bar
// qs.stringify({ foo: bar }, true); ---> ?foo=bar
// qs.stringify({ foo: bar }, '&');  ---> &foo=bar
// qs.stringify({ foo: '' }, '&');   ---> &foo=

import assert from 'assert'; //todo kim-stamp qs用来断言

const { Option } = Select;
const FormItem = Form.Item;

function fetch({ url, keywords, initial = '运' }, callback) {
  let timeout;
  let currentValue;
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  currentValue = keywords;

  function request() {
    // const str = querystring.encode({ code: 'utf-8', name: value });
    // axios.ajax({ url: `${LOGISTICS_PATH}/web/port/nameType?portType=1&${str}` })
    let count = 0;
    axios
      .ajax({
        url: `${url}`,
        params: {
          name: keywords || '',
        },
      })
      .then(res => {
        if (currentValue === keywords) {
          let data = [];
          res.content &&
            res.content.list.map(item => {
              // console.log(item, '中覅u');
              data.push({
                value: item.id,
                text: item.portName,
              });
            });
          callback(data);
        }
      });
  }

  timeout = setTimeout(request, 100);
}

export default class SearchInput extends React.Component {
  state = {
    data: [],
    value: undefined,
  };

  handleSearch = value => {
    if (value) {
      fetch(value, data => this.setState({ data }));
    } else {
      this.setState({ data: [] });
    }
  };

  handleChange = value => {
    this.setState({ value });
  };

  render() {
    const options = this.state.data.map(item => <Option key={item.value}>{item.text}</Option>);
    const { url, placeholder } = this.props;
    return (
      <Select
        allowClear
        showSearch
        autoFocus
        placeholder={placeholder || '请输入'}
        style={this.props.style}
        defaultActiveFirstOption={false}
        showArrow={false}
        filterOption={false}
        onSearch={keywords =>
          fetch(
            {
              url,
              keywords,
            },
            data => this.setState({ data }),
          )
        }
        onChange={(keywords, options) => {
          this.setState({ keywords });
          this.props.onChange && this.props.onChange(keywords);
        }}
        notFoundContent={null}
      >
        {options}
        {this.props.children}
      </Select>
    );
  }
}
